package com.fmatos.amazingwallpapers.view.albums;

import javax.inject.Inject;

import android.app.Activity;
import android.app.Fragment;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.fmatos.amazingwallpapers.R;
import com.fmatos.amazingwallpapers.dagger.AmazingApplication;
import com.fmatos.amazingwallpapers.image.AsyncCloudManager;
import com.fmatos.amazingwallpapers.image.database.orm.DatabaseManager;


public class AlbumsActivity extends Activity {

	private static final String TAG = AlbumsActivity.class.getSimpleName();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_albums);
		if (savedInstanceState == null) {
			getFragmentManager()
					.beginTransaction()
					.add(R.id.container, new PlaceholderFragment(this))
					.commit();
		}
		
		Log.i(TAG, "creating " + getClass() + " at " + System.currentTimeMillis());

	}
	
	@Override
	protected void onResume() {
		super.onResume();
		DatabaseManager.acquireDatabase(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		DatabaseManager.releaseDatabase();
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater()
				.inflate(R.menu.albums, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item
				.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super
				.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		
		@Inject AlbumsAdapter adapter;
		@Inject AsyncCloudManager asyncManager;

		public PlaceholderFragment(Activity activity) {
			((AmazingApplication) activity.getApplication()).inject(this,activity);
		}

		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			
			
			final View rootView = inflater
					.inflate(R.layout.fragment_albums, container, false);
			
			ListView list = (ListView)rootView.findViewById(R.id.listAlbums);
			
			list.setAdapter(adapter);

			
            final ImageButton btnDeleteOldImages = (ImageButton) rootView.findViewById(R.id.imgBtnDeleteOld);

            btnDeleteOldImages.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    btnDeleteOldImages.setImageDrawable(rootView.getResources().getDrawable(android.R.drawable.ic_menu_report_image));
                }
            });


            final ImageButton btnRefreshAllAlbums = (ImageButton) rootView.findViewById(R.id.imgBtnRefreshAllAlbums);

            btnRefreshAllAlbums.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                	refreshImages(rootView.getResources().getDrawable(android.R.drawable.stat_sys_download ),
                			rootView.getResources().getDrawable(R.drawable.ic_menu_refresh ),
                			btnRefreshAllAlbums);
            }
            });
            
			if ( adapter.getCount() == 0 ) {
				Toast.makeText(getActivity(), "No albums found, loading albums list from server.", Toast.LENGTH_LONG).show();
				btnRefreshAllAlbums.callOnClick();
			}

            final ImageButton btnDownloadImages = (ImageButton) rootView.findViewById(R.id.imgBtnDownloadImagesFromAlbums);

            btnDownloadImages.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnDownloadImages.setImageDrawable(rootView.getResources().getDrawable(android.R.drawable.stat_sys_download
                    		));

                }
            });

			return rootView;
		}
		
		private void refreshImages(final Drawable drawableInit,final Drawable drawableFinish,final ImageButton btnRefreshAllAlbums) {
            btnRefreshAllAlbums.setImageDrawable(drawableInit);
//            asyncManager = new AsyncCloudManager(getActivity());
            asyncManager.refreshAlbumList(new Runnable() {
				
				@Override
				public void run() {
					btnRefreshAllAlbums.setImageDrawable(drawableFinish);
					adapter.notifyDataSetChanged();
					Log.i(TAG,"Dataset invalidated");
				}
			});

		}
		
		@Override
		public void onResume() {

//			adapter = new AlbumsAdapter(getActivity());
//			list.setAdapter(adapter);
			
//			asyncManager = null;
			super.onResume();
		}

		@Override
		public void onPause() {
			if ( adapter != null) {
				adapter.releaseResources();
			}
			super.onPause();
		}

		@Override
		public void onDestroyView() {
			if ( adapter != null) {
				adapter.releaseResources();
			}
			super.onDestroyView();
			
			if ( asyncManager == null ) {
//				asyncManager = new AsyncCloudManager(getActivity());
			}
		}

	}
}
